<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>用户管理</title>
    <link rel="stylesheet" href="../res/layui/css/layui.css">
    <style>
        .layui-table td, .layui-table th {
            text-align: center;
        }
        .search-area {
            margin-bottom: 10px;
        }
        #userInfoDialog {
            padding: 20px;
            width: 500px;
            display: none;
        }
        #userForm .layui-form-item {
            margin-bottom: 15px;
        }
        .status-enable {
            color: green;
        }
        .status-disable {
            color: red;
        }
    </style>
</head>
<body>
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-header">用户管理</div>
        <div class="layui-card-body">
            <!-- 搜索区域 -->
            <div class="search-area">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">用户名</label>
                        <div class="layui-input-inline">
                            <input type="text" id="searchUsername" placeholder="请输入用户名" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">手机号</label>
                        <div class="layui-input-inline">
                            <input type="text" id="searchPhone" placeholder="请输入手机号" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <button class="layui-btn" id="searchBtn">
                            <i class="layui-icon layui-icon-search"></i>搜索
                        </button>
                        <button class="layui-btn layui-btn-primary" id="resetBtn">重置</button>
                    </div>
                </div>
            </div>
            
            <!-- 工具栏 -->
            <div class="layui-btn-container">
                <button class="layui-btn" id="addUserBtn">
                    <i class="layui-icon layui-icon-add-1"></i>添加用户
                </button>
            </div>
            
            <!-- 用户列表表格 -->
            <table id="userTable" lay-filter="userFilter"></table>
        </div>
    </div>
</div>

<!-- 用户信息对话框 -->
<div id="userInfoDialog">
    <form class="layui-form" id="userForm" lay-filter="userForm">
        <input type="hidden" name="id" id="userId">
        <div class="layui-form-item">
            <label class="layui-form-label">用户名</label>
            <div class="layui-input-block">
                <input type="text" name="username" id="username" placeholder="请输入用户名" class="layui-input" lay-verify="required">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">昵称</label>
            <div class="layui-input-block">
                <input type="text" name="nickname" id="nickname" placeholder="请输入昵称" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">密码</label>
            <div class="layui-input-block">
                <input type="password" name="password" id="password" placeholder="请输入密码" class="layui-input" lay-verify="required">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">手机号</label>
            <div class="layui-input-block">
                <input type="text" name="phone" id="phone" placeholder="请输入手机号" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">邮箱</label>
            <div class="layui-input-block">
                <input type="text" name="email" id="email" placeholder="请输入邮箱" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">性别</label>
            <div class="layui-input-block">
                <input type="radio" name="sex" value="男" title="男" checked>
                <input type="radio" name="sex" value="女" title="女">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">状态</label>
            <div class="layui-input-block">
                <input type="radio" name="status" value="1" title="正常" checked>
                <input type="radio" name="status" value="0" title="禁用">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="userSubmit">保存</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
</div>

<script src="../res/layui/layui.js"></script>
<script>
    layui.use(['table', 'layer', 'form', 'jquery'], function () {
        var table = layui.table;
        var layer = layui.layer;
        var form = layui.form;
        var $ = layui.jquery;
        
        // 渲染用户表格
        var userTable = table.render({
            elem: '#userTable',
            url: '/user/list',
            method: 'get',
            page: true,
            limit: 5,
            limits: [5, 10, 20],
            cols: [[
                {field: 'id', title: 'ID', width: 80, sort: true},
                {field: 'username', title: '用户名', width: 120},
                {field: 'nickname', title: '昵称', width: 120},
                {field: 'phone', title: '手机号', width: 150},
                {field: 'email', title: '邮箱', width: 180},
                {field: 'sex', title: '性别', width: 80},
                {field: 'createTime', title: '注册时间', width: 180, templet: function(d) {
                    return d.createTime ? new Date(d.createTime).toLocaleString() : '';
                }},
                {field: 'status', title: '状态', width: 100, templet: function(d) {
                    return d.status === 1 ? 
                        '<span class="status-enable">正常</span>' : 
                        '<span class="status-disable">禁用</span>';
                }},
                {title: '操作', width: 200, align: 'center', toolbar: '#rowTools'}
            ]],
            response: {
                statusCode: 200
            },
            parseData: function(res) {
                return {
                    code: res.code,
                    msg: res.msg,
                    count: res.data.total,
                    data: res.data.records
                };
            }
        });
        
        // 监听工具栏事件
        table.on('tool(userFilter)', function(obj) {
            var data = obj.data;
            var layEvent = obj.event;
            
            if (layEvent === 'details') {
                // 查看详情
                showUserInfo(data);
            } else if (layEvent === 'del') {
                // 删除用户
                deleteUser(data.id);
            } else if (layEvent === 'edit') {
                // 编辑用户
                editUser(data);
            } else if (layEvent === 'updateStatus') {
                // 更新状态
                var newStatus = data.status === 1 ? 0 : 1;
                var statusText = newStatus === 1 ? '启用' : '禁用';
                layer.confirm('确定要' + statusText + '该用户吗？', function(index) {
                    $.ajax({
                        url: '/user/status',
                        method: 'PUT',
                        data: {
                            id: data.id,
                            status: newStatus
                        },
                    }).done(function(res) {
                        if (res.code === 200) {
                            layer.msg(statusText + '成功');
                            obj.update({
                                status: newStatus
                            });
                        } else {
                            layer.msg(res.msg || statusText + '失败');
                        }
                    }).fail(function() {
                        layer.msg('请求失败');
                    }).always(function() {
                        layer.close(index);
                    });
                });
            } else if (layEvent === 'addToBlacklist') {
                // 添加到黑名单
                addToBlacklist(data);
            }
                        success: function(res) {
                            if (res.code === 200) {
                                layer.msg('状态更新成功');
                                obj.update({
                                    status: newStatus
                                });
                            } else {
                                layer.msg(res.msg || '状态更新失败');
                            }
                        },
                        error: function() {
                            layer.msg('请求失败');
                        }
                    });
                    layer.close(index);
                });
            } else if (layEvent === 'addToBlacklist') {
                // 添加到黑名单
                addToBlacklist(data);
            }
        });
        
        // 添加用户按钮点击事件
        $('#addUserBtn').click(function() {
            openUserDialog();
        });
        
        // 搜索按钮点击事件
        $('#searchBtn').click(function() {
            var username = $('#searchUsername').val();
            var phone = $('#searchPhone').val();
            
            // 这里可以添加搜索逻辑
            table.reload('userTable', {
                where: {
                    username: username,
                    phone: phone
                },
                page: {
                    curr: 1
                }
            });
        });
        
        // 重置按钮点击事件
        $('#resetBtn').click(function() {
            $('#searchUsername').val('');
            $('#searchPhone').val('');
            table.reload('userTable', {
                where: {},
                page: {
                    curr: 1
                }
            });
        });
        
        // 表单提交
        form.on('submit(userSubmit)', function(data) {
            var formData = data.field;
            var url = formData.id ? '/user/update' : '/user/add';
            var method = formData.id ? 'PUT' : 'POST';
            
            $.ajax({
                url: url,
                method: method,
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function(res) {
                    if (res.code === 200) {
                        layer.msg(formData.id ? '更新成功' : '添加成功');
                        layer.closeAll('page');
                        table.reload('userTable');
                    } else {
                        layer.msg(res.msg || (formData.id ? '更新失败' : '添加失败'));
                    }
                },
                error: function() {
                    layer.msg('请求失败');
                }
            });
            
            return false;
        });
        
        // 打开用户对话框
        function openUserDialog(userData) {
            // 重置表单
            $('#userForm')[0].reset();
            
            if (userData) {
                // 编辑模式，填充数据
                form.val('userForm', {
                    'id': userData.id,
                    'username': userData.username,
                    'nickname': userData.nickname,
                    'password': '', // 编辑时不显示原密码
                    'phone': userData.phone,
                    'email': userData.email,
                    'sex': userData.sex,
                    'status': userData.status
                });
                $('#password').removeAttr('lay-verify');
            } else {
                // 新增模式
                $('#password').attr('lay-verify', 'required');
            }
            
            layer.open({
                type: 1,
                title: userData ? '编辑用户' : '添加用户',
                content: $('#userInfoDialog'),
                area: ['550px', '550px'],
                success: function() {
                    form.render();
                }
            });
        }
        
        // 编辑用户
        function editUser(userData) {
            openUserDialog(userData);
        }
        
        // 删除用户
        function deleteUser(userId) {
            layer.confirm('确定要删除该用户吗？', function(index) {
                $.ajax({
                    url: '/user/delete',
                    method: 'DELETE',
                    data: {
                        id: userId
                    },
                    success: function(res) {
                        if (res.code === 200) {
                            layer.msg('删除成功');
                            table.reload('userTable');
                        } else {
                            layer.msg(res.msg || '删除失败');
                        }
                    },
                    error: function() {
                        layer.msg('请求失败');
                    }
                });
                layer.close(index);
            });
        }
        
        // 显示用户详情
        function showUserInfo(userData) {
            var content = '<div class="layui-tab layui-tab-brief" lay-filter="userDetailTab">' +
                '<ul class="layui-tab-title">' +
                '  <li class="layui-this">基本信息</li>' +
                '  <li>黑名单记录</li>' +
                '</ul>' +
                '<div class="layui-tab-content">' +
                '  <div class="layui-tab-item layui-show">' +
                '    <table class="layui-table">' +
                '      <tr><td style="width: 100px;">用户名:</td><td>' + (userData.username || '') + '</td></tr>' +
                '      <tr><td>昵称:</td><td>' + (userData.nickname || '') + '</td></tr>' +
                '      <tr><td>手机号:</td><td>' + (userData.phone || '') + '</td></tr>' +
                '      <tr><td>邮箱:</td><td>' + (userData.email || '') + '</td></tr>' +
                '      <tr><td>性别:</td><td>' + (userData.sex === '1' ? '男' : (userData.sex === '0' ? '女' : (userData.sex || ''))) + '</td></tr>' +
                '      <tr><td>注册时间:</td><td>' + (userData.createTime ? new Date(userData.createTime).toLocaleString() : '') + '</td></tr>' +
                '      <tr><td>状态:</td><td>' + (userData.status === 1 ? '正常' : '禁用') + '</td></tr>' +
                '    </table>' +
                '  </div>' +
                '  <div class="layui-tab-item">' +
                '    <div id="userBlacklistRecords" style="padding: 10px;">' +
                '      <p style="text-align: center;">加载中...</p>' +
                '    </div>' +
                '  </div>' +
                '</div>' +
                '</div>';
                
            layer.open({
                type: 1,
                title: '用户详情 - ' + (userData.username || ''),
                content: content,
                area: ['500px', '400px'],
                success: function(layero, index) {
                    layui.use('element', function() {
                        var element = layui.element;
                        element.render('tab');
                    });
                    
                    // 加载黑名单记录
                    loadUserBlacklistRecords(userData.id);
                }
            });
        }
        
        // 加载用户黑名单记录
        function loadUserBlacklistRecords(userId) {
            $.ajax({
                url: '/blacklist/listByUserId',
                method: 'GET',
                data: {
                    userId: userId
                },
                success: function(res) {
                    if (res.code === 200) {
                        var records = res.data || [];
                        var recordsHtml = '';
                        
                        if (records.length > 0) {
                            recordsHtml += '<table class="layui-table">' +
                                '<thead>' +
                                '<tr>' +
                                '  <th>拉黑原因</th>' +
                                '  <th>拉黑时间</th>' +
                                '  <th>操作人</th>' +
                                '</tr>' +
                                '</thead>' +
                                '<tbody>';
                                
                            records.forEach(function(record) {
                                recordsHtml += '<tr>' +
                                    '<td>' + (record.reason || '') + '</td>' +
                                    '<td>' + (record.createTime ? new Date(record.createTime).toLocaleString() : '') + '</td>' +
                                    '<td>' + (record.operator || '') + '</td>' +
                                    '</tr>';
                            });
                            
                            recordsHtml += '</tbody></table>';
                        } else {
                            recordsHtml = '<p style="text-align: center; color: #999;">暂无黑名单记录</p>';
                        }
                        
                        $('#userBlacklistRecords').html(recordsHtml);
                    } else {
                        $('#userBlacklistRecords').html('<p style="text-align: center; color: red;">加载黑名单记录失败: ' + (res.msg || '') + '</p>');
                    }
                },
                error: function() {
                    $('#userBlacklistRecords').html('<p style="text-align: center; color: red;">请求失败</p>');
                }
            });
        }
        
        // 添加到黑名单
        function addToBlacklist(userData) {
            layer.prompt({
                formType: 2,
                title: '请输入拉黑原因',
                area: ['300px', '100px']
            }, function(value, index, elem) {
                $.ajax({
                    url: '/blacklist/add',
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        userId: userData.id,
                        reason: value,
                        operator: '管理员'
                    }),
                    success: function(res) {
                        if (res.code === 200) {
                            layer.msg('已添加到黑名单');
                            // 重新加载用户表格
                            table.reload('userTable');
                        } else {
                            layer.msg(res.msg || '添加失败');
                        }
                    },
                    error: function() {
                        layer.msg('请求失败');
                    }
                });
                layer.close(index);
            });
        }
    });
</script>

<!-- 操作栏自定义模板 -->
<script id="rowTools" type="text/html">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-normal layui-btn-xs" lay-event="details">
            <i class="layui-icon layui-icon-list"></i>详情
        </button>
        <button class="layui-btn layui-btn-xs" lay-event="edit">
            <i class="layui-icon layui-icon-edit"></i>编辑
        </button>
        <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">
            <i class="layui-icon layui-icon-delete"></i>删除
        </button>
        {{# if(d.status === 0){ }}
        <button class="layui-btn layui-btn-warm layui-btn-xs" lay-event="updateStatus">
            <i class="layui-icon layui-icon-close-fill"></i>禁用
        </button>
        {{# }else{ }}
        <button class="layui-btn layui-btn-normal layui-btn-xs" lay-event="updateStatus">
            <i class="layui-icon layui-icon-ok-circle"></i>启用
        </button>
        {{# } }}
        <button class="layui-btn layui-btn-primary layui-btn-xs" lay-event="addToBlacklist">
            <i class="layui-icon layui-icon-close"></i>拉黑
        </button>
    </div>
</script>

</body>
</html>